<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="主键" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入主键"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户" prop="mchId">
        <el-select v-model="queryParams.mchId" clearable filterable placeholder="请选择商户" size="small">
          <el-option
            v-for="dept in deptList"
            :key="dept.deptId"
            :label="dept.deptName"
            :value="dept.deptId"
          >
            <span style="float: left">{{ dept.deptName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ dept.deptId }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户ID" prop="customerId">
        <el-input
          v-model="queryParams.customerId"
          placeholder="请输入客户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="薪资单位" prop="hourlyRateCalculation">
        <el-select v-model="queryParams.salaryUnit" placeholder="请选择薪资单位" clearable>
          <el-option
            v-for="dict in dict.type.salary_unit"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable>
          <el-option
            v-for="dict in dict.type.customer_salaryaudit_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="项目所属工地" prop="worksiteId">
        <el-select v-model="queryParams.worksiteId" clearable filterable placeholder="请选择所属工地" size="small">
          <el-option
            v-for="worksite in worksiteList"
            :key="worksite.id"
            :label="worksite.name"
            :value="worksite.id"
          >
            <span style="float: left">{{ worksite.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ worksite.id }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属项目" prop="projectId">
        <el-select v-model="queryParams.projectId" clearable filterable placeholder="请选择所属工地" size="small">
          <el-option
            v-for="project in projectList"
            :key="project.id"
            :label="project.name"
            :value="project.id"
          >
            <span style="float: left">{{ project.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ project.id }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目负责人" prop="responsiblePersonId">
        <el-select v-model="queryParams.responsiblePersonId" clearable filterable placeholder="请选择公司负责人" size="small">
          <el-option
            v-for="user in userList"
            :key="user.dictValue"
            :label="user.dictLabel"
            :value="user.dictValue"
          >
            <span style="float: left">{{ user.dictLabel }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ user.dictValue }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发放状态" prop="paymentStatus">
        <el-select v-model="queryParams.paymentStatus" placeholder="请选择发放状态" clearable>
          <el-option
            v-for="dict in dict.type.customer_salary_payment_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="签卡开始时间">
        <el-date-picker
          v-model="daterangeSignInStartTime"
          style="width: 335px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="签卡结束时间">
        <el-date-picker
          v-model="daterangeSignInEndTime"
          style="width: 335px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-check"
          size="mini"
          :disabled="multiple"
          @click="handleAudits"
          v-hasPermi="['hrcrm:salary:audit']"
        >审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-s-marketing"
          size="mini"
          :disabled="multiple"
          @click="handleSettles"
          v-hasPermi="['hrcrm:salary:settle']"
        >结算</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-s-claim"
          size="mini"
          :disabled="multiple"
          @click="handleGrant"
          v-hasPermi="['hrcrm:salary:grant']"
        >发放薪资</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hrcrm:salary:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['hrcrm:salary:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hrcrm:salary:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hrcrm:salary:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="salaryList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="商户" align="center" prop="mchId" width="100">
        <template slot-scope="scope">
          <span v-for="dept in deptList">
            <span v-if="dept.deptId == scope.row.mchId">{{dept.deptName}}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="客户" align="center" prop="customerName" width="150" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.customerName }}（{{ scope.row.customerId }}）</span>
        </template>
      </el-table-column>
      <el-table-column label="签卡开始时间" align="center" prop="signInStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signInStartTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签卡结束时间" align="center" prop="signInEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signInEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签卡时长" align="center" prop="workDuration" width="100" />
      <el-table-column label="薪资单位" align="center" prop="salaryUnit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.salary_unit" :value="scope.row.salaryUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="单位薪资" align="center" prop="salaryRate" />
      <el-table-column label="薪资计算方式" align="center" prop="hourlyRateCalculation" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.salary_calculation_method" :value="scope.row.hourlyRateCalculation"/>
        </template>
      </el-table-column>
      <el-table-column label="所属工地" align="center" prop="worksiteId" width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-for="worksite in worksiteList">
            <span v-if="worksite.id == scope.row.worksiteId">{{worksite.name}}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="所属项目" align="center" prop="projectId" width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-for="project in projectList">
            <span v-if="project.id == scope.row.projectId">{{project.name}}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="项目负责人" align="center" prop="responsiblePersonId" width="100">
        <template slot-scope="scope">
          <span v-for="user in userList">
            <span v-if="user.dictValue == scope.row.responsiblePersonId">{{user.dictLabel}}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="薪资" align="center" prop="salaryAmount" />
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.customer_salaryaudit_status" :value="scope.row.auditStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="发放状态" align="center" prop="paymentStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.customer_salary_payment_status" :value="scope.row.paymentStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" width="200" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['hrcrm:salary:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hrcrm:salary:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户薪资记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" style="width: 95%;">
        <el-form-item label="商户" prop="mchId">
          <el-select v-model="form.mchId" clearable filterable placeholder="请选择商户">
            <el-option
              v-for="dept in deptList"
              :key="dept.deptId"
              :label="dept.deptName"
              :value="dept.deptId"
            >
              <span style="float: left">{{ dept.deptName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ dept.deptId }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户ID" prop="customerId">
          <el-input v-model="form.customerId" placeholder="请输入客户ID" />
        </el-form-item>
        <el-form-item label="签卡开始时间" prop="signInStartTime">
          <el-date-picker clearable
            v-model="form.signInStartTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择签卡开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="签卡结束时间" prop="signInEndTime">
          <el-date-picker clearable
            v-model="form.signInEndTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择签卡结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所属项目" prop="projectId">
          <el-select v-model="form.projectId" clearable filterable placeholder="请选择所属项目">
            <el-option
              v-for="project in projectList"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            >
              <span style="float: left">{{ project.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ project.id }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="薪资" prop="salaryAmount">
          <el-input v-model="form.salaryAmount" placeholder="请输入薪资" />
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus">
          <el-select v-model="form.auditStatus" placeholder="请选择审核状态">
            <el-option
              v-for="dict in dict.type.customer_salaryaudit_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发放状态" prop="paymentStatus">
          <el-radio-group v-model="form.paymentStatus">
            <el-radio
              v-for="dict in dict.type.customer_salary_payment_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSalary, getSalary, delSalary, addSalary, updateSalary, audits, settle, grant } from "@/api/hrcrm/salary";
import {getInfo} from "@/api/login";
import {allDept} from "@/api/system/dept";
import {getUserList} from "@/api/system/user";
import {allWorksite} from "@/api/hrcrm/worksite";
import {allProject} from "@/api/hrcrm/project";

export default {
  name: "Salary",
  dicts: ['customer_salaryaudit_status', 'customer_salary_payment_status', 'salary_calculation_method', 'salary_unit'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户薪资记录表格数据
      salaryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeSignInStartTime: [],
      // 备注时间范围
      daterangeSignInEndTime: [],

      // 二级部门列表
      deptList: [],
      // 是否部门领导
      isLeader: true,
      // 是否管理员
      isAdmin: false,
      userParams: [],
      // 用户列表
      userList: [],
      loginUserId: null,

      // 工地列表
      worksiteList: [],
      // 项目
      projectList: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: this.$route.query && this.$route.query.id || null,
        mchId: null,
        customerId: null,
        signInStartTime: null,
        signInEndTime: null,
        workDuration: null,
        salaryRate: null,
        hourlyRateCalculation: null,
        worksiteId: null,
        projectId: null,
        responsiblePersonId: null,
        salaryAmount: null,
        auditStatus: null,
        paymentStatus: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        mchId: [
          { required: true, message: "商户ID不能为空", trigger: "blur" }
        ],
        customerId: [
          { required: true, message: "客户ID不能为空", trigger: "blur" }
        ],
        signInStartTime: [
          { required: true, message: "签卡开始时间不能为空", trigger: "blur" }
        ],
        signInEndTime: [
          { required: true, message: "签卡结束时间不能为空", trigger: "blur" }
        ],
        workDuration: [
          { required: true, message: "签卡时长不能为空", trigger: "blur" }
        ],
        projectId: [
          { required: true, message: "所属项目不能为空", trigger: "blur" }
        ],
        salaryAmount: [
          { required: true, message: "薪资不能为空", trigger: "blur" }
        ],
        auditStatus: [
          { required: true, message: "审核状态不能为空", trigger: "change" }
        ],
        paymentStatus: [
          { required: true, message: "发放状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.init();
  },
  activated() {
    this.init();
  },
  methods: {
    init() {
      this.queryParams.id = this.$route.query && this.$route.query.id || null;
      getInfo().then(
        res => {
          if (!res.isAdmin && !res.isLeader) {
            this.isLeader = false;
          }
          if (res.isAdmin) {
            this.isAdmin = true;
          }
          //登录用户ID赋值
          this.loginUserId = res.user.userId;
          //拉取部门
          allDept().then(response => {
            this.deptList = response.data
            this.initUserList(this.deptList[0].deptId)
            this.initWorksiteList(this.deptList[0].deptId)
            this.initProjectList(this.deptList[0].deptId)
            if(!this.isAdmin){
              this.queryParams.mchId.push(this.deptList[0].deptId);
            }
            this.getList();
          });
        })
    },
    /** 选中部门的Id*/
    initUserList(deptId) {
      this.userList=[];
      this.userParams.deptId=deptId
      if(!this.isLeader){
        this.userParams.userId=this.loginUserId;
      }
      getUserList(this.userParams).then(response => {
        this.userList = response.data;
      });
    },
    /** 工地列表 */
    initWorksiteList(mchId) {
      allWorksite('{"mchId": "' + mchId + '"}').then(response => {
        this.worksiteList = response.rows
      })
    },
    /** 项目列表 */
    initProjectList(mchId) {
      allProject('{"mchId": "' + mchId + '"}').then(response => {
        this.projectList = response.rows
      })
    },
    /** 查询客户薪资记录列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeSignInStartTime && '' != this.daterangeSignInStartTime) {
        this.queryParams.params["beginSignInStartTime"] = this.daterangeSignInStartTime[0];
        this.queryParams.params["endSignInStartTime"] = this.daterangeSignInStartTime[1];
      }
      if (null != this.daterangeSignInEndTime && '' != this.daterangeSignInEndTime) {
        this.queryParams.params["beginSignInEndTime"] = this.daterangeSignInEndTime[0];
        this.queryParams.params["endSignInEndTime"] = this.daterangeSignInEndTime[1];
      }
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      if (null != this.daterangeUpdateTime && '' != this.daterangeUpdateTime) {
        this.queryParams.params["beginUpdateTime"] = this.daterangeUpdateTime[0];
        this.queryParams.params["endUpdateTime"] = this.daterangeUpdateTime[1];
      }
      listSalary(this.queryParams).then(response => {
        this.salaryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        mchId: null,
        customerId: null,
        signInStartTime: null,
        signInEndTime: null,
        workDuration: null,
        salaryRate: null,
        hourlyRateCalculation: null,
        worksiteId: null,
        projectId: null,
        responsiblePersonId: null,
        salaryAmount: null,
        auditStatus: null,
        paymentStatus: 'WAITING',
        createTime: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeSignInStartTime = [];
      this.daterangeSignInEndTime = [];
      this.daterangeCreateTime = [];
      this.daterangeUpdateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户薪资记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSalary(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户薪资记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSalary(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSalary(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除客户薪资记录编号为"' + ids + '"的数据项？').then(function() {
        return delSalary(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hrcrm/salary/export', {
        ...this.queryParams
      }, `salary_${new Date().getTime()}.xlsx`)
    },
    /** 签卡审核 */
    handleAudits(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否批量审核ID为"' + ids + '"的签卡数据项？').then(function() {
        return audits(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("审核成功");
      }).catch(() => {});
    },
    /** 结算 */
    handleSettles(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('请确保，结算前签卡记录已经审核通过。是否批量结算ID为"' + ids + '"的签卡数据项？').then(function() {
        return settle(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("结算成功");
      }).catch(() => {});
    },
    /** 发放薪资 */
    handleGrant(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('请确保，发放薪资前，已经结算薪资。是否批量发放ID为"' + ids + '"的薪资？').then(function() {
        return grant(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("发放成功");
      }).catch(() => {});
    },
  }
};
</script>
